#include <stdio.h>
#include <stdlib.h>
#include <libspe2.h>
#include <pthread.h>

#define SPE_NUM 1

typedef union {
  float f;
  int i;
} Number;

void* run_context(void*);

int main( int argc, char** argv )
{
  int ret;
  
  srand48(0);

  spe_context_ptr_t spe[SPE_NUM];
  spe_program_handle_t *prog;
  int i;
  pthread_t threads[SPE_NUM];

  prog = spe_image_open("com_spe.elf");

  for( i = 0; i<SPE_NUM; i++ ) {
    spe[i] = spe_context_create(0, NULL);
    ret = spe_program_load(spe[i], prog);
  }
  
  for( i = 0; i<SPE_NUM; i++ ) {
    pthread_create( &threads[i], NULL, run_context, &spe[i] );
  }

  // try and get a message from the spe
  Number x;
  //unsigned int *x_ptr;
  //float *x_flt_ptr;

  while( !spe_out_mbox_status(spe[0]) ) {
    printf("waiting\n");
  }

  spe_out_mbox_read(spe[0], &(x.i), 1);
  //x_flt_ptr = (float*)x_ptr;
  printf("The spe sent me: %f\n", x.f);

  for( i = 0; i<SPE_NUM; i++ ) {
    pthread_join( threads[i], NULL );
  }

  for( i = 0; i<SPE_NUM; i++ ) {
     ret = spe_context_destroy(spe[i]);
  }
  
  ret = spe_image_close(prog);

  return 0;
}

void* run_context(void* thread_args)
{
  int ret;
  unsigned int entry = SPE_DEFAULT_ENTRY;
  spe_stop_info_t stop_info;
  spe_context_ptr_t* spe_ptr = (spe_context_ptr_t*)thread_args;

  ret = spe_context_run( *spe_ptr, &entry, 0, NULL, NULL, &stop_info);

  return NULL;
}
